package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"
)

type sCouponRecord struct {
}

var insCouponRecord = sCouponRecord{}

func CouponRecord() *sCouponRecord {
	return &insCouponRecord
}

// CouponReceiveList  领取优惠券记录列表
func (s *sCouponRecord) CouponReceiveList(ctx context.Context, req *api.CouponReceiveListReq) (res *model.CouponRecordListRes, err error) {
	r := g.RequestFromCtx(ctx)
	var couponList []*model.CouponRecordIdAndUserAndCouponInfoRes
	var userId = &model.UserIdReq{
		Id: req.UserId,
	}
	var couponId = &model.CouponIdReq{
		Id: "",
	}
	// 查询优惠券id
	if req.CouponName != "" {
		if err = dao.LotCoupon.Ctx(ctx).Where("coupon_name", req.CouponName).Scan(&couponId); err != nil {
			response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有查询该优惠券")
		}
	}
	// 查询用户详情
	if req.Username != "" {
		if err = dao.LotUser.Ctx(ctx).Where("username", req.Username).Scan(&userId); err != nil {
			response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有查询用户名")
		}
	}
	startNum, endNum := paging.Paging(req.Paging)
	condition := g.Map{
		"id":        req.Id,      // 优惠券记录id
		"coupon_id": couponId.Id, // 优惠券id
		"user_id":   userId.Id,   // 用户id

	}
	// 定义dao的基本查询
	var sqlInfo = dao.LotCouponRecord.Ctx(ctx).OmitEmpty().WithAll().Where(condition)
	// 1 已核销该优惠券  -1 未核销该优惠券
	if req.IsUse == 1 {
		sqlInfo = sqlInfo.WhereNotNull("use_time")
	}
	if req.IsUse == -1 {
		sqlInfo = sqlInfo.WhereNull("use_time")
	}
	// 获取优惠券记录列表
	if err = sqlInfo.OrderDesc("updated_at").Limit(startNum, endNum).Scan(&couponList); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	// 获取总条数
	countInfo, err := sqlInfo.Count()
	putCount := paging.PutCount(req.Paging, countInfo)
	res = &model.CouponRecordListRes{
		List:    couponList,
		PutPage: *putCount,
	}
	return res, err
}
